<template>
  <el-dialog @open="openDialog" :title="isAdd?'新增':'编辑'" :visible="dialogFormVisible" @close="closeDialog">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules" >
      <el-form-item label="头像" prop="avatar">
        <el-upload
          accept=".png,.jpg,.jpeg"
          class="avatar-uploader"
          :action="host+'/guard/upload?module=guardUser'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="form.avatar" :src="form.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="用户名" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="真实姓名" prop="real_name">
        <el-input v-model="form.real_name"></el-input>
      </el-form-item>
      <el-form-item v-if="isAdd" label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item v-if="isAdd" label="确认密码" prop="repassword">
        <el-input type="password" v-model="form.repassword"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" >
        <el-input type="email" v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="selectRoleIds">
        <el-select v-model="form.selectRoleIds" multiple placeholder="请选择">
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="激活" prop="is_available">
        <el-switch
          :active-value="1"
          :inactive-value="2"
          v-model="form.status"
          active-text="是"
          inactive-text="否">
        </el-switch>
      </el-form-item>

      <el-form-item label="备注">
        <el-input :rows="3" type="textarea" v-model="form.beizhu"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>

import {myGet,myPost} from "@/utils/myUtils";

const urlAdd = '/guard/rbac/guardUser/add'
const urlRole = '/guard/rbac/role/lst'

export default {
  name: "AddGuardUserDialog",
  props:{
    dialogFormVisible:{
      type:Boolean,
      default:false
    },
    record:{
      type:Object,
      default:{}
    }
  },

  data(){
    let checkPhone = (rule, value, callback) => {
      const reg = /^[1][3-9][0-9]{9}$/;
      if (value == '' || value == undefined || value == null) {
        callback();
      } else {
        if ((!reg.test(value)) && value != '') {
          callback(new Error('请输入正确的电话号码'));
        } else {
          callback();
        }
      }
    };
    let reg = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{6,12}$/
    var validateNewPwd = (rule, value, callback) => {
      if (!reg.test(value)) {
        callback(new Error('密码应是6-12位数字、字母或字符！'))
      } /*else if (this.form.oldPasswd === value) {
                callback(new Error('新密码与旧密码不可一致！'))
            } */ else {
        callback()
      }
    }
    var validateComfirmPwd = (rule, value, callback) => {
      if (!reg.test(value)) {
        callback(new Error('密码应是6-12位数字、字母或字符！'))
      } else if (this.form.password !== value) {
        callback(new Error('确认密码与新密码不一致！'))
      } else {
        callback()
      }
    }
    return {
      form: {
        id: 0,
        name: '',
        real_name: '',
        phone: '',
        email: '',
        beizhu: '',
        avatar: '',
        password: '',
        status: 1,
        selectRoleIds: [],
      },
      rules: {
        name: [
          {required: true, message: '必填', trigger: 'blur'}
        ],
        real_name: [
          {required: true, min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机', trigger: 'blur'},
          {validator: checkPhone, trigger: 'blur'}
        ],
        selectRoleIds: [
          {required: true, type: 'array', message: '至少选择一个角色', trigger: ['change', 'blur']}
        ],
        password: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {validator: validateNewPwd, trigger: 'blur'}
        ],
        repassword: [
          {required: true, message: '请输入确认密码', trigger: 'blur'},
          {validator: validateComfirmPwd, trigger: 'blur'}
        ]
      },
      roles:[],
      host:process.env.VUE_APP_HOST
    }
  },
  methods:{

    handleAvatarSuccess(res, file) {
      if(res.status){
        this.form.avatar = res.data.records.filePath
      }else{
        this.$message.error('上传失败!')
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },

    onSubmit(){
      myPost(urlAdd,this.form).then(res=>{
        if(res){
          this.$message.success(res.msg)
          this.$emit('success',false)
        }
      })
    },
    cancel(){
      this.$emit('cancelDialog',false)
      Object.assign(this.$data.form, this.$options.data().form)
    },
    closeDialog(){
      this.cancel()
    },
    openDialog(){
      Object.assign(this.$data.form, this.$options.data().form)
      this.getRoles()
      //record有数据说明是编辑
      if(Object.keys(this.record).length>0){
        this.form.id = this.record.id
        this.form.avatar = this.record.avatar
        this.form.real_name = this.record.real_name
        this.form.name = this.record.name
        this.form.phone = this.record.phone
        this.form.email = this.record.email
        this.form.beizhu = this.record.beizhu
        let roleIds = this.record.role_ids.split(',');
        for (let i = 0; i <roleIds.length ; i++) {
          roleIds[i] = parseInt(roleIds[i])
        }
        this.form.selectRoleIds = roleIds
      }
    },

    getRoles(){
      myGet(urlRole).then((res)=>{
        this.roles = res.data.records
      })
    },
  },

  computed: {
    isAdd: function() {
      return Object.keys(this.record).length<=0;
    }
  },

}
</script>

<style scoped>

</style>
